package com.xj.demo;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class ManagerHttpServer {
    // 定义时间格式器（线程安全）
    private static final DateTimeFormatter TIME_FORMATTER =
            DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    // 默认端口号
    private static final int DEFAULT_PORT = 90;

    public static void main(String[] args) throws IOException {
        // 解析端口参数（如果未传入参数，则使用默认值90）
        int port = args.length > 0 ? Integer.parseInt(args[0]) : DEFAULT_PORT;

        // 创建HTTP服务器，绑定到指定端口
        HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);

        // 设置"/hello"路径的处理程序
        server.createContext("/hello", new HelloHandler());

        // 启动服务器
        server.start();
        System.out.println("Server started on port " + port + ". Press ENTER to exit.");

        // 保持服务器运行
        // System.in.read();
        // server.stop(0);
    }

    static class HelloHandler implements HttpHandler {
        @Override
        public void handle(HttpExchange exchange) throws IOException {
            // 验证请求方法
            if (!"GET".equalsIgnoreCase(exchange.getRequestMethod())) {
                exchange.sendResponseHeaders(405, -1);
                exchange.close();
                return;
            }

            // 生成带完整时间戳的响应
            String timestamp = LocalDateTime.now().format(TIME_FORMATTER);
            String response = "access success " + timestamp;

            // 配置响应参数
            exchange.getResponseHeaders().set("Content-Type", "text/plain; charset=UTF-8");
            byte[] responseData = response.getBytes("UTF-8");

            // 发送响应
            exchange.sendResponseHeaders(200, responseData.length);
            try (OutputStream os = exchange.getResponseBody()) {
                os.write(responseData);
            }
        }
    }
}
